package com.woniuxy.meal.controller.consumer;


import cn.hutool.json.JSONUtil;
import com.woniuxy.meal.common.RedisKey;
import com.woniuxy.meal.entity.UserCart;
import com.woniuxy.meal.form.message.DeleteCartMessage;
import com.woniuxy.meal.service.UserCartService;
import com.woniuxy.meal.util.RedisUtil;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


@Component
@RocketMQMessageListener(consumerGroup = "cart",topic = "carts_del")
public class DelCartConsumer implements RocketMQListener<DeleteCartMessage> {

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private UserCartService userCartService;

    @Transactional
    @Override
    public void onMessage(DeleteCartMessage message) {
        String userCartKey = RedisKey.getUserCartKey(message.getUserId());
        List<Long> cartIds = new ArrayList<>();
        for (Long foodId : message.getFoodIds()) {
            String cartInfoKey = RedisKey.getCartInfoKey(foodId);
            try {
                Object o = redisUtil.hsGet(userCartKey, cartInfoKey);
                UserCart userCart = JSONUtil.toBean(String.valueOf(o), UserCart.class);
                cartIds.add(userCart.getId());
                redisUtil.hsDel(userCartKey,cartInfoKey);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        userCartService.removeByIds(cartIds);
    }
}
